package com.zp.security.jwt.handler;

import com.zp.common.base.entity.LoginToken;
import com.zp.common.base.resp.BaseResp;
import com.zp.common.base.utils.JwtUtils;
import com.zp.common.base.utils.ResponseUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录认证成功处理器
 * AbstractAuthenticationProcessingFilter调用successfulAuthentication方法
 *
 * @author zp
 */
@Component
@RequiredArgsConstructor
public class LoginAuthenticationSuccessHandler  implements AuthenticationSuccessHandler {

    private  final JwtUtils jwtTokenUtil;


    /**
     * 身份验证成功,我们通常在这里下发令牌
     *
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //todo 业务逻辑 例如用户通用信息等
        //生成令牌
        String accessToken = jwtTokenUtil.createToken(userDetails.getUsername());
        //生成刷新令牌
        String refreshToken = jwtTokenUtil.refreshToken(accessToken);
        renderToken(response, LoginToken.builder().accessToken(accessToken).refreshToken(refreshToken).build());
    }
    /**
     * 渲染返回 token 数据,因为前端页面接收的都是Result对象，故使用application/json返回
     */
    public void renderToken(HttpServletResponse response, LoginToken token) throws IOException {
        ResponseUtils.result(response,new BaseResp("200","登录成功！",token));
    }
}
